Using the HTML5 Filesystem API by Eric Bidelman

Using the HTML5 Filesystem API by Eric Bidelman

Author:Eric Bidelman [Eric Bidelman]
Language: eng
Format: epub, mobi, pdf
Tags: COMPUTERS / Programming Languages / JavaScript
ISBN: 9781449309442
Publisher: O'Reilly Media
Published: 2011-07-21T16:00:00+00:00


Using Copy and Paste

A final way to import files involves pasting files in your application. This is done by setting up and onpaste handler on the document body and iterating through the event’s clipboardData items. Each item has a “kind” and “type” property. Checking the “kind” property can be used to verify whether or not a pasted item is a file. If item.kind == “file”, then the item is indeed a file.

The following example sets up an onpaste listener on the page, allowing users to paste in .pngs. The images/items are then read as Blobs using getAsFile(), and written into the filesystem.

Example 4-10. Pasting a file into an application and saving it to the filesystem

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Pasting a file into an application and saving it to the filesystem</title> </head> <body> <p> Copy an image from the Web (right-click > Copy Image), click in this window, and paste it in. </p> <script> // Take care of vendor prefixes. window.requestFileSystem = window.requestFileSystem || window.webkiRequestFileSystem; window.URL = window.URL || window.webkitURL; var onError = function(e) { console.log('There was an error', e); }; /** * Writes a Blob to the filesystem. * * @param {DirectoryEntry} dir The directory to write the blob into. * @param {Blob} blob The data to write. * @param {string} fileName A name for the file. * @param {function(ProgressEvent)} opt_callback An optional callback. * Invoked when the write completes. */ var writeBlob = function(dir, blob, fileName, opt_callback) { dir.getFile(fileName, {create: true}, function(fileEntry) { fileEntry.createWriter(function(writer) { if (opt_callback) { writer.onwrite = opt_callback; } writer.write(blob); }, onError); }, onError); }; // Setup onpaste handler to catch dropped .png files. document.body.onpaste = function(e) { var items = e.clipboardData.items; for (var i = 0; i < items.length; ++i) { if (items[i].kind == 'file' && items[i].type == 'image/png') { var blob = items[i].getAsFile(); writeBlob(FS.root, blob, 'MyPastedImage', function(e) { console.log('Write completed.'); }); } } }; va FS; // cache the FileSystem object for later. window.requestFileSystem(TEMPORARY, 1024*1024 /*1MB*/, function(fs) { FS = fs; }, onError); </script> </body> </html>



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.